package com.ysg.binding.viewadapter;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.BindingAdapter;
import androidx.databinding.InverseBindingAdapter;
import androidx.databinding.InverseBindingListener;

import com.ysg.binding.command.BindingCommand;
import com.ysg.utils.YStringUtil;
import com.ysg.widget.row.YRowItem;

public class RowItemAdapter {

    /**
     * Switch的状态改变监听
     */
    @BindingAdapter("onSwitchChangeCommand")
    public static void onSwitchChangeCommand(final YRowItem rowItem, final BindingCommand<Boolean> changeListener) {
        if (changeListener != null) {
            rowItem.getSwitch().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeListener.execute(rowItem.getSwitch().isChecked());
                }
            });
        }
    }


    @BindingAdapter("bindContent")
    public static void setText(YRowItem rowEdit, String text) {
        String oldText = rowEdit.getText();
        if (YStringUtil.noEq(oldText, text)){
            rowEdit.setText(text);
        }
    }

    @InverseBindingAdapter(attribute = "bindContent", event = "textChanged")
    public static String getText(YRowItem rowEdit) {
        return rowEdit.getText();
    }

    @BindingAdapter(value = "textChanged", requireAll = false)
    public static void setListener(YRowItem rowEdit, final InverseBindingListener listener) {
        if (listener != null) {
            rowEdit.getEditText().addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (listener != null){
                        listener.onChange();
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
        }
    }






}
